<template>
  <div class="products">
    <div class="filter-section">
      <el-card>
        <template #header>
          <div class="filter-header">
            <span>筛选条件</span>
            <el-button text @click="resetFilters">重置筛选</el-button>
          </div>
        </template>
        
        <!-- 分类筛选 -->
        <div class="filter-group">
          <h3>商品分类</h3>
          <el-radio-group v-model="filters.category">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="flowers">鲜花</el-radio-button>
            <el-radio-button label="gifts">文创产品</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 价格范围 -->
        <div class="filter-group">
          <h3>价格范围</h3>
          <el-slider
            v-model="filters.priceRange"
            range
            :min="0"
            :max="2000"
            :step="50"
            :marks="priceMarks"
          />
        </div>

        <!-- 花材选择 -->
        <!-- <div class="filter-group" v-if="filters.category === 'flowers'">
          <h3>花材选择</h3>
          <el-select
            v-model="filters.flowerTypes"
            multiple
            placeholder="选择花材"
            style="width: 100%"
          >
            <el-option
              v-for="type in flowerTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </div> -->
      </el-card>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品"
        :prefix-icon="Search"
        clearable
      >
        <template #append>
          <el-button :icon="Search" />
        </template>
      </el-input>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <el-row :gutter="20">
        <el-col
          v-for="product in filteredProducts"
          :key="product.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="product-card" :body-style="{ padding: '0px' }">
            <img :src="product.imageUrl || '/placeholder.png'" class="product-image">
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p class="description">{{ product.description }}</p>
              <div class="price-action">
                <span class="price">¥{{ product.price }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalProducts"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getCreativeProductList, getFlowerList } from '@/api/product'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref, watch } from 'vue'
import { useStore } from 'vuex'

export default {
  name: 'ProductList',
  setup() {
    const store = useStore()
    const loading = ref(false)
    const filters = ref({
      category: 'all',
      priceRange: [0, 2000],
      flowerTypes: []
    })

    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(12)

    const flowerTypes = [
      { label: '玫瑰', value: 'rose' },
      { label: '百合', value: 'lily' },
      { label: '康乃馨', value: 'carnation' },
      { label: '向日葵', value: 'sunflower' },
      { label: '郁金香', value: 'tulip' }
    ]

    const priceMarks = {
      0: '¥0',
      500: '¥500',
      1000: '¥1000',
      1500: '¥1500',
      2000: '¥2000'
    }

    // 商品数据
    const products = ref([])
    const totalProducts = ref(0)

    // 加载商品数据
    const loadProducts = async () => {
      loading.value = true
      try {
        let result
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          name: searchQuery.value || undefined
        }

        if (filters.value.category === 'all' || filters.value.category === 'flowers') {
          try {
            const flowerRes = await getFlowerList(params)
            result = flowerRes.records.map(item => ({
              ...item,
              type: 'flower'
            }))
            totalProducts.value = flowerRes.total
          } catch (error) {
            console.error('Failed to load flowers:', error)
            ElMessage.error('加载鲜花数据失败')
          }
        }

        if (filters.value.category === 'all' || filters.value.category === 'gifts') {
          try {
            const giftRes = await getCreativeProductList(params)
            const giftProducts = giftRes.records.map(item => ({
              ...item,
              type: 'gift'
            }))
            if (filters.value.category === 'all') {
              result = [...(result || []), ...giftProducts]
              totalProducts.value += giftRes.total
            } else {
              result = giftProducts
              totalProducts.value = giftRes.total
            }
          } catch (error) {
            console.error('Failed to load creative products:', error)
            ElMessage.error('加载文创产品失败')
          }
        }

        products.value = result || []
      } catch (error) {
        console.error('Failed to load products:', error)
        ElMessage.error('加载商品数据失败')
      } finally {
        loading.value = false
      }
    }

    // 过滤商品
    const filteredProducts = computed(() => {
      return products.value.filter(product => {
        // 价格筛选
        if (product.price < filters.value.priceRange[0] || 
            product.price > filters.value.priceRange[1]) {
          return false
        }

        // 花材筛选（仅对花卉商品）
        if (product.type === 'flower' && 
            filters.value.flowerTypes.length > 0 && 
            !product.flowerTypes?.some(t => filters.value.flowerTypes.includes(t))) {
          return false
        }

        return true
      })
    })

    const resetFilters = () => {
      filters.value = {
        category: 'all',
        priceRange: [0, 2000],
        flowerTypes: []
      }
      searchQuery.value = ''
      loadProducts()
    }

    const addToCart = (product) => {
      store.commit('addToCart', product)
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      loadProducts()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadProducts()
    }

    // 监听筛选条件变化
    watch([() => filters.value.category, searchQuery], () => {
      currentPage.value = 1
      loadProducts()
    })

    onMounted(() => {
      loadProducts()
    })

    return {
      filters,
      searchQuery,
      currentPage,
      pageSize,
      flowerTypes,
      priceMarks,
      filteredProducts,
      totalProducts,
      loading,
      resetFilters,
      addToCart,
      handleSizeChange,
      handleCurrentChange,
      Search
    }
  }
}
</script>

<style lang="scss" scoped>
.products {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;

  .filter-section {
    margin-bottom: 20px;

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .filter-group {
      margin-bottom: 20px;

      h3 {
        margin-bottom: 10px;
        font-size: 16px;
        color: #333;
      }

      .el-check-tag {
        margin: 0 8px 8px 0;
      }
    }
  }

  .search-bar {
    margin-bottom: 20px;
  }

  .product-list {
    margin-bottom: 20px;

    .product-card {
      margin-bottom: 20px;
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      .product-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
      }

      .product-info {
        padding: 14px;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #333;
        }

        .description {
          margin: 8px 0;
          font-size: 14px;
          color: #666;
          height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .price-action {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            color: #f56c6c;
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }
  }

  .pagination {
    text-align: center;
    margin-top: 30px;
  }
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

.product-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.description {
  font-size: 14px;
  color: #666;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
}
</style> 